//
// Created by guanj on 16-3-15.
//

#include "rc4.h"

#include "../log/CLog.h"

static LOG_CREATE_FUNC_DEBUG(__FILE__)

uint8_t *rc4_init(const uint8_t *key, int32_t key_size, uint8_t *s_box, int32_t box_size) {
    for (int32_t i = 0; i < box_size; ++i) {
        s_box[i] = i;
    }
    int32_t j = 0;
    for (int32_t i = 0; i < box_size; ++i) {
        j = (j + s_box[i] + key[i % key_size]) % box_size;
        swap(s_box[i], s_box[j]);
    }
    return s_box;
}

uint8_t *rc4_crypt(uint8_t *data, int32_t size, uint8_t *s_box, int32_t box_size) {
    int32_t i = 0, j = 0;
    for (int k = 0; k < size; ++k) {
        i = (i + 1) % box_size;
        j = (j + s_box[i]) % box_size;
        swap(s_box[i], s_box[j]);
        data[k] ^= s_box[(s_box[i] + s_box[j]) & box_size];
    }
    return data;
}
